'use client';

import { useEffect, useState } from 'react';
import { useSearchParams } from 'next/navigation';
import Link from 'next/link';
import { Button } from '@/components/ui/button';
import { AlertCircle, RefreshCw, Wifi, Globe } from 'lucide-react';

export default function AuthErrorPage() {
  const searchParams = useSearchParams();
  const [errorMessage, setErrorMessage] = useState<string>('');
  const [errorDetails, setErrorDetails] = useState<string>('');
  const [errorType, setErrorType] = useState<string>('default');
  const [isRetrying, setIsRetrying] = useState<boolean>(false);
  const [retryCount, setRetryCount] = useState<number>(0);
  const [networkIssue, setNetworkIssue] = useState<boolean>(false);

  useEffect(() => {
    const error = searchParams.get('error');
    const errorDescription = searchParams.get('error_description') || '';
    
    // 检查是否是网络错误
    const isNetworkError = 
      errorDescription.toLowerCase().includes('econnreset') || 
      errorDescription.toLowerCase().includes('network') ||
      errorDescription.toLowerCase().includes('connection') ||
      errorDescription.toLowerCase().includes('timeout');
    
    setNetworkIssue(isNetworkError);
    
    if (error) {
      switch (error) {
        case 'Configuration':
          setErrorType('config');
          setErrorMessage('服务器配置错误');
          setErrorDetails('OAuth提供商配置有问题，请联系管理员');
          break;
        case 'AccessDenied':
          setErrorType('access');
          setErrorMessage('访问被拒绝');
          setErrorDetails('您取消了登录授权或提供商拒绝了访问');
          break;
        case 'Verification':
          setErrorType('verification');
          setErrorMessage('验证错误');
          setErrorDetails('无法验证您的账户信息');
          break;
        case 'OAuthCallback':
          setErrorType('oauth');
          if (isNetworkError) {
            setErrorMessage('网络连接错误');
            setErrorDetails('与认证服务器通信时发生网络错误，可能是网络连接不稳定导致');
          } else {
            setErrorMessage('OAuth回调错误');
            setErrorDetails('与认证服务器通信时发生错误，可能是网络连接问题');
          }
          break;
        case 'OAuthSignin':
          setErrorType('oauth');
          setErrorMessage('OAuth登录初始化失败');
          setErrorDetails('无法启动OAuth登录流程，请尝试其他登录方式');
          break;
        case 'OAuthAccountNotLinked':
          setErrorType('account');
          setErrorMessage('账号未关联');
          setErrorDetails('此邮箱已使用其他方式登录，请使用原登录方式');
          break;
        case 'EmailSignin':
          setErrorType('email');
          setErrorMessage('邮箱登录错误');
          setErrorDetails('发送登录链接时出错，请检查您的邮箱地址');
          break;
        case 'CredentialsSignin':
          setErrorType('credentials');
          setErrorMessage('凭据错误');
          setErrorDetails('邮箱或密码不正确');
          break;
        case 'SessionRequired':
          setErrorType('session');
          setErrorMessage('需要登录');
          setErrorDetails('您需要登录才能访问此页面');
          break;
        case 'Default':
        default:
          setErrorType('default');
          setErrorMessage('登录失败');
          setErrorDetails(errorDescription || '登录过程中发生未知错误，请稍后重试');
          break;
      }
    } else {
      setErrorType('default');
      setErrorMessage('登录失败');
      setErrorDetails('登录过程中发生未知错误，请稍后重试');
    }
  }, [searchParams]);

  // 自动重试登录
  const handleRetry = () => {
    if (retryCount >= 3) return;
    
    setIsRetrying(true);
    setRetryCount(prev => prev + 1);
    
    // 延迟后重定向到登录页
    setTimeout(() => {
      window.location.href = '/auth/login';
    }, 2000);
  };

  // 如果是网络错误，自动尝试重试
  useEffect(() => {
    if (networkIssue && retryCount < 2) {
      handleRetry();
    }
  }, [networkIssue]);

  return (
    <div className="flex items-center justify-center min-h-screen bg-gray-100 dark:bg-gray-900">
      <div className="w-full max-w-md p-8 space-y-8 bg-white rounded-lg shadow-md dark:bg-gray-800">
        <div className="text-center">
          {/* 根据错误类型显示不同的图标 */}
          <div className="flex justify-center mb-4">
            {errorType === 'oauth' || networkIssue ? (
              <Globe className="h-12 w-12 text-amber-500" />
            ) : (
              <AlertCircle className="h-12 w-12 text-red-500" />
            )}
          </div>
          
          <h1 className="text-2xl font-bold text-red-600 dark:text-red-400">
            {errorMessage}
          </h1>
          <div className="mt-2 text-gray-600 dark:text-gray-400">
            {errorDetails}
          </div>
          
          {/* 显示重试状态 */}
          {isRetrying && (
            <div className="mt-4 flex items-center justify-center gap-2 text-sm text-amber-600">
              <RefreshCw className="h-4 w-4 animate-spin" />
              <span>正在重试 ({retryCount}/3)...</span>
            </div>
          )}
        </div>

        <div className="mt-6 space-y-4">
          {!isRetrying && (
            <Button
              className="w-full"
              onClick={handleRetry}
              disabled={retryCount >= 3}
            >
              {retryCount > 0 ? '再次尝试' : '重试登录'}
            </Button>
          )}
          
          <Button
            variant="outline"
            className="w-full"
            asChild
          >
            <Link href="/auth/login">
              返回登录页面
            </Link>
          </Button>
          
          {networkIssue && (
            <div className="mt-4 p-4 bg-blue-50 dark:bg-blue-900/30 rounded-md">
              <h3 className="flex items-center gap-2 text-sm font-medium text-blue-700 dark:text-blue-400">
                <Wifi className="h-4 w-4" />
                网络连接问题
              </h3>
              <ul className="mt-2 list-disc list-inside text-left text-sm text-gray-600 dark:text-gray-400">
                <li>检查您的网络连接是否稳定</li>
                <li>如果使用VPN或代理，请尝试关闭后重试</li>
                <li>尝试使用其他浏览器或设备</li>
                <li>如果问题持续，请尝试使用邮箱密码登录</li>
              </ul>
            </div>
          )}
          
          <div className="text-center text-sm text-gray-500 dark:text-gray-400">
            <p>如果问题持续存在，请尝试以下解决方案：</p>
            <ul className="mt-2 list-disc list-inside text-left">
              <li>清除浏览器缓存和Cookie</li>
              <li>尝试使用其他浏览器</li>
              <li>检查您的网络连接</li>
              <li>尝试其他登录方式</li>
            </ul>
          </div>
        </div>
      </div>
    </div>
  );
}